package cn.lsg.util;

import java.io.BufferedInputStream;
import java.io.InputStream;

import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import org.apache.commons.io.output.ByteArrayOutputStream;

/**
 * Http 工具类
 * 
 */
public class UtilHttp {

	// 文件类型
	private static final Map<String, String> FileType = new HashMap<String, String>();
	// 扩展名匹配正则
	private static final String FileExtReg = "\\.([^\\.]*)$";

	static {
		FileType.put("image/jpeg", "jpg");
		FileType.put("image/x-png", "png");
		FileType.put("image/gif", "gif");
		FileType.put("image/png", "png");
		FileType.put("application/x-shockwave-flash", "swf");
	}

	/**
	 * 文件类型转扩展名
	 * 
	 * */
	private synchronized final static String parseFileExtension(String type) {
		Iterator<Entry<String, String>> iter = FileType.entrySet().iterator();
		String ext = null;
		while (iter.hasNext()) {
			Map.Entry<String, String> entry = iter.next();
			if (type.indexOf(entry.getKey()) != -1) {
				ext = entry.getValue();
				break;
			}
		}
		return ext;
	}

	/**
	 * 获取 页面 内容
	 * 
	 * @param url
	 *            URL地址
	 * @return URL字符内容
	 * @throws Exception
	 */
	public final String getURLContent(String url) throws Exception {
		String encode = "UTF-8";
		URLConnection conn = createURLConnection(url);
		String contentType = conn.getHeaderField("Content-Type");
		if (contentType != null) {
			Matcher m = Pattern.compile("charset=(.*)").matcher(contentType);
			m.find();
			encode = m.group(1);
		}
		return new String(download(url).toByteArray(), encode);
	}

	public final ByteArrayOutputStream download(String url) throws Exception {
		URLConnection conn = null;
		InputStream bis = null;

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		url = url.replaceAll("( *)$", "");
		url = UtilEncrypt.URIEncode(url);
		try {
			conn = createURLConnection(url);
			bis = new BufferedInputStream(conn.getInputStream());
			byte[] bit = new byte[1024];
			int len = 0;
			if ("gzip".equals(conn.getContentEncoding())) {
				bis = new GZIPInputStream(bis);
			}
			while ((len = bis.read(bit)) != -1) {
				baos.write(bit, 0, len);
			}
		} finally {
			if (conn != null) {
			}
			if (bis != null) {
				bis.close();
			}
			baos.flush();
			baos.close();
		}

		return baos;
	}

	/**
	 * 文件扩展名读取
	 * 
	 * @param path
	 *            文件绝对路径
	 * 
	 * */

	public synchronized final static String getExt(String path)
			throws Exception {
		String ext = null;
		try {
			if (path.indexOf("http://") == 0) {
				URLConnection conn = createURLConnection(path);
				String ContentType = conn.getHeaderField("Content-Type");
				ext = parseFileExtension(ContentType);
			} else {
				Matcher m = Pattern.compile(FileExtReg).matcher(path);
				if (m.find()) {
					ext = m.group(1);
				}
			}
			if (by.isNull(ext)) {
				throw new Exception("未知扩展名");
			}
		} catch (Exception e) {
			throw new Exception("文件扩展名获取异常：" + e.getMessage());
		}
		return ext;
	}

	/**
	 * URLConnection连接
	 * */
	public synchronized final static URLConnection createURLConnection(
			String url) throws Exception {
		URLConnection conn = new URL(url).openConnection();
		// 请求头部信息
		conn.setRequestProperty("Host", conn.getURL().getHost());
		conn.setRequestProperty("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		conn.setRequestProperty("Accept-Language",
				"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
		conn.setRequestProperty("Accept-Encoding", "gzip");
		conn.setRequestProperty("Referer", conn.getURL().toExternalForm());
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setRequestProperty(
				"User-Agent",
				"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0");
		conn.setConnectTimeout(3000);
		conn.connect();
		return conn;
	}

}
